package cn.emall.controller;

import cn.emall.config.AsyncEmail;
import cn.emall.config.JwtProperties;
import cn.emall.pojo.User;
import cn.emall.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import token.common.pojo.UserInfo;
import token.common.util.JwtUtil;
import utils.CookieUtil;
import utils.ResponseBean;
import utils.ResultCode;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.util.Date;


@RestController
@RequestMapping("/user")
@Api(value = "用户接口")
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private AsyncEmail asyncEmail;
    @Autowired
    private RestTemplate restTemplate;

    @Value("${server.port}")
    private String port;

    @RequestMapping(value = "/getAllUsers",method = RequestMethod.GET)
    @ApiOperation(value = "获得所有用户", notes = "直接获得")
    public ResponseBean getAllUsers(){
        System.out.println("进入getAllUsers方法！！！");
        System.out.println("我是端口为："+this.port);
        return ResponseBean.success(ResultCode.FIND_MANYDATA_SUCCESS,userService.list());

    }
    @ApiOperation(value = "获得单个用户", notes = "根据用户名和密码获取")
    @GetMapping("/queryUser/{username}/{password}")
    public ResponseBean queryUser(@PathVariable String username,@PathVariable String password){
        User user=userService.getOne(new QueryWrapper<User>().eq("username",username).
                eq("password", password));
        if(user==null){
            return ResponseBean.failure(ResultCode.FIND_DATA_FAILURE);
        }
        return ResponseBean.success(ResultCode.FIND_DATA_SUCCESS, user);
    }
    @PostMapping("/test")
    public ResponseBean test(@RequestBody User user){
        System.out.println(user);
        return ResponseBean.success(user);

    }
    @GetMapping("/test/Cookie")
    public ResponseBean testCookie(@CookieValue(value="EMALL_TOKEN")Cookie cookie)throws Exception{
        System.out.println(cookie);
        UserInfo userInfo=JwtUtil.getInfoFromToken(cookie.getValue(),jwtProperties.getPublicKey());
        return ResponseBean.success(userInfo);
    }
    @ApiOperation(value = "获得用户个人详细信息", notes = "根据cookie中的token的userId")
    @GetMapping("/getUserInfo")
    public ResponseBean getUserInfo(@CookieValue(value="EMALL_TOKEN")Cookie cookie)throws Exception{
        UserInfo userInfo=JwtUtil.getInfoFromToken(cookie.getValue(),jwtProperties.getPublicKey());
        User user=userService.getById(userInfo.getId());
        return ResponseBean.success(ResultCode.FIND_DATA_SUCCESS,user);

    }
    @ApiOperation(value = "更新用户的密码", notes = "需要在登录状态下修改密码")
    @GetMapping(value = "/updateUserPassword/{password}")
    public ResponseBean updatePassword(@CookieValue(value="EMALL_TOKEN")Cookie cookie,@PathVariable String password,
                                       HttpServletRequest request, HttpServletResponse response)throws Exception{
        UserInfo userInfo=JwtUtil.getInfoFromToken(cookie.getValue(),jwtProperties.getPublicKey());
        User user=userService.getById(userInfo.getId());
        user.setPassword(password);
        User u=new User();
        u.setId(user.getId());
        u.setPassword(password);
        u.setUpdateTime(new Date());
        userService.updateById(u);

        ResponseBean responseBean=restTemplate.getForObject("http://token-service/getToken/"+user.getUsername()+"/"+user.getPassword(),ResponseBean.class);
        CookieUtil.setCookie(request,response,this.jwtProperties.getCookieName(),responseBean.getData().toString(),this.jwtProperties.getExpire()*60);
        return ResponseBean.success(ResultCode.UPDATE_DATA_SUCCESS);

    }
    @ApiOperation(value = "更新用户的邮箱或手机号", notes = "需要在登录状态下更新邮箱或手机号")
    @GetMapping(value = "/updateUserInfo/{email}/{phone}")
    public ResponseBean updateUserInfo(@CookieValue(value="EMALL_TOKEN")Cookie cookie,@PathVariable String email,
                                       @PathVariable String phone)throws Exception{
        UserInfo userInfo=JwtUtil.getInfoFromToken(cookie.getValue(),jwtProperties.getPublicKey());
        User user=userService.getById(userInfo.getId());
        User u=new User();
        u.setId(user.getId());
        if(email!=null){
            u.setEmail(email);
        }
        if(phone!=null){
            u.setPhone(phone);
        }
        u.setUpdateTime(new Date());
        userService.updateById(u);
        return ResponseBean.success(ResultCode.UPDATE_DATA_SUCCESS);

    }
    @GetMapping("/testRedis/{code}")
    public ResponseBean testRedis(@PathVariable String code){
        redisTemplate.opsForValue().set("email",code);
        return ResponseBean.success(redisTemplate.opsForValue().get("email"));

    }
    @ApiOperation(value = "发送邮箱验证码", notes = "需要邮箱地址")
    @GetMapping("/sendMailCode/{email}")
    public ResponseBean sendMailCode(@PathVariable String email){
        System.out.println("-----------------");
        asyncEmail.testMail(email,redisTemplate);
        System.out.println("------------------");
        return ResponseBean.success(ResultCode.MAIL_CODE_SUCCESS);
    }
    @ApiOperation(value = "用户注册", notes = "需要用户注册信息和邮箱验证码")
    @PostMapping("/register/{emailCode}")
    public ResponseBean register(@RequestBody User user, @PathVariable String emailCode, HttpServletRequest request, HttpServletResponse response){
        //1.对比数据库有没有此用户名
        // 2.比较邮箱验证码
        // 3.写入数据库
        // 4. 颁发token
        User u=userService.getOne(new QueryWrapper<User>().eq("username",user.getUsername()));
        if(u!=null){
            return ResponseBean.failure(ResultCode.USER_HAS_EXISTED);
        }
        String code=redisTemplate.opsForValue().get(user.getEmail());
        if(code==null){
            return ResponseBean.failure(ResultCode.MAIL_CODE_EXPIRE);
        }
        if(!code.equals(emailCode)){
            return ResponseBean.failure(ResultCode.MAIL_CODE_ERROR);
        }
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userService.save(user);
        /**
         * 下面这一段代码需要和前端进行联调
         */
         ResponseBean responseBean=restTemplate.getForObject("http://token-service/getToken/"+user.getUsername()+"/"+user.getPassword(),ResponseBean.class);
        System.out.println(responseBean.getData());
        CookieUtil.setCookie(request,response,this.jwtProperties.getCookieName(),responseBean.getData().toString(),this.jwtProperties.getExpire()*60);
        return ResponseBean.success(ResultCode.USER_REGISTER_SUCCESS);
    }
    @ApiOperation(value = "用户登录", notes = "需要用户名和密码")
    @GetMapping("/login/{username}/{password}")
    public ResponseBean login(@PathVariable String username,@PathVariable String password,
                              HttpServletRequest request, HttpServletResponse response){
        User user=userService.getOne(new QueryWrapper<User>().eq("username",username).eq("password",password));
        System.out.println(user);
        if(user==null){
            return ResponseBean.failure(ResultCode.USER_LOGIN_ERROR);
        }
        ResponseBean responseBean=restTemplate.getForObject("http://token-service/getToken/"+user.getUsername()+"/"+user.getPassword(),ResponseBean.class);
        CookieUtil.setCookie(request,response,this.jwtProperties.getCookieName(),responseBean.getData().toString(),this.jwtProperties.getExpire()*60);
       //response.setHeader("EMALL_TOKEN",responseBean.getData().toString());
        return ResponseBean.success(ResultCode.LOGIN_SUCCESS,responseBean.getData());
    }
    @ApiOperation(value = "用户密码找回", notes = "需要用户提供问题的答案")
    @GetMapping("/getBackPassword/{answer}")
    public ResponseBean getBackPassword(@CookieValue(value="EMALL_TOKEN")Cookie cookie,@PathVariable String answer)throws Exception{
        UserInfo userInfo=JwtUtil.getInfoFromToken(cookie.getValue(),jwtProperties.getPublicKey());
        User user=userService.getById(userInfo.getId());
        if(!user.getAnswer().equals(answer)){
            return ResponseBean.failure(ResultCode.ANSWER_WRONG);
        }
        return ResponseBean.success(ResultCode.ANSWER_RIGHT,user.getPassword());
    }



}
